package com.maoshi.shop.mp.comment.api.controller;

import com.maoshi.shop.common.exception.MaoshiShopBindException;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/p/wx/jsapi")
@AllArgsConstructor
public class JsapiController {

    private final WxMpService wxMpService;

    @PostMapping("/createJsapiSignature")
    @ApiOperation(value = "生成jsapi签名", notes = "根据url生成当前页面的jsapi签名")
    public ResponseEntity<WxJsapiSignature> createJsapiSignature(@RequestBody String url) {
        WxJsapiSignature jsapiSignature;
        try {
            jsapiSignature = wxMpService.createJsapiSignature(url);
        } catch (WxErrorException e) {
            throw new MaoshiShopBindException(e.getError().toString());
        }

        return ResponseEntity.ok(jsapiSignature);
    }
}
